package com.example.administrator.day01_08;

import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private MediaPlayer player;
    private String path;
    private ListView songsLv;
    private String currentSong;
    private String[] fileList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        player=new MediaPlayer();
        songsLv= (ListView) findViewById(R.id.songs_lv);//找到歌的id
        path= Environment.getExternalStorageDirectory().getPath()+"/mp3";//找到歌的路径

        fileList=new File(path).list();
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fileList);
        songsLv.setAdapter(adapter);

        songsLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentSong=path+"/"+fileList[position];
            }
        });

    }

    public void play(View view) {
        try {
            player.reset();
            player.setDataSource(currentSong);
            player.prepare();
            player.start();
//            if(player.isPlaying()){
//                player.pause();
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void pause(View view) {
        player.pause();
    }
}
